package com.example.listener.handler;

import com.example.annotation.MQListener;
import com.example.dto.MQListenerDto;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 * @className: SysMQMessageListenerHandler
 * @author: chentao
 * @date: 2025/3/20 下午4:41
 * @Version: 1.0
 * @description:
 */
public class SysMQMessageListenerHandler implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Map<String, MQListenerDto> listenerMap = new ConcurrentHashMap<String, MQListenerDto>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAnnotationPresent(MQListener.class)) {
            MQListener mqListener = bean.getClass().getAnnotation(MQListener.class);
            MQListenerDto mqListenerDto = new MQListenerDto(mqListener);
            mqListenerDto.setBeanName(beanName);
            this.listenerMap.put(mqListener.name(), mqListenerDto);
        }
        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public Map<String, MQListenerDto> getListenerMap() {
        return listenerMap;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
